import PySimpleGUI as sg
import django
import check_code
import time
import threading
import re
import os

def print_t(x):
    print(f'{time.strftime("%Y-%m-%d %T")} {x}')


def main():
    sg.theme('Dark Blue 3')
    layout = [[sg.Text('开源软件仓库关键词监控', font='Default 18')],
              [sg.T('关键词（多个关键词使用空格分割）', size=(30, 1)),
               sg.Input(key='keywords', size=(35, 1))],
              [sg.T('收件人（多个收件人使用分号隔开）', size=(30, 1)),
               sg.Input(key='receivers', size=(35, 1))],
              [sg.T('频率（间隔的分钟数）', size=(30, 1)), sg.Input(
                  key='freq', default_text=5, size=(35, 1))],
              [sg.Button('开始监控'), sg.Button('退出程序')],
              [sg.Output(size=(65, 20))]]

    window = sg.Window('github，gitee monitor', layout, font=('Any 14'))

    is_alive = False
    while True:  # Event Loop
        event, values = window.read()
        if event in (sg.WIN_CLOSED, '退出程序'):
            window.close()
            os.kill(os.getpid(), 9)
            os.system('kill $PPID')
            break
        if event == '开始监控' and is_alive == False:
            print_t("开始监控")
            receivers = [x for x in re.split(
                ';|；', values['receivers']) if x != '']
            keywords = re.split('\s+', values["keywords"])
            if keywords == ['']:
                print_t("请输入关键词，多个关键词请用空格分割")
                continue
            try:
                freq = int(values['freq'])
            except:
                print_t("请输入正确的数字")
                continue
            if is_alive == False:
                threading.Thread(target=check_code.main, args=(
                    keywords, freq, receivers)).start()
                is_alive = True
        time.sleep(0.1)

if __name__ == "__main__":
    django.setup()
    main()
